package com.hfb.mashibing.alip8.juc.c020;


import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 信号量:允许参数个线程同时执行,支持公平/非公平
 * 一般用于限流
 */

public class T11_TestSemaphore {
    public static void main(String[] args) {
        // 允许参数个线程同时执行
        Semaphore semaphore = new Semaphore(1);
//        Semaphore semaphore = new Semaphore(2, true);

        new Thread(()->{
            try {
                // 获取信号量，此方法是阻塞方法
                semaphore.acquire();
                System.out.println("T1 running 。。。");

                Thread.sleep(200);
                System.out.println("T1 running 。。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 恢复
                semaphore.release();
            }
        },"T1").start();


        new Thread(()->{
            try {
                // 获取信号量，此方法是阻塞方法
                semaphore.acquire();
                System.out.println("T2 running 。。。");

                Thread.sleep(200);
                System.out.println("T2 running 。。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 恢复
                semaphore.release();
            }
        },"T2").start();


    }
}
